package com.xixi.easy.rpc.proxy;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.xixi.easy.rpc.model.RpcRequest;
import com.xixi.easy.rpc.model.RpcResponse;
import com.xixi.easy.rpc.serializer.CustomJdkSerializer;
import com.xixi.easy.rpc.serializer.CustomSerializer;

import java.io.IOException;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * @author: zxh
 * @date: 2024/8/21 14:06
 * @description: 动态代理
 */
public class ServiceProxy implements InvocationHandler {

	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		// 指定序列化器
		CustomSerializer serializer = new CustomJdkSerializer();

		System.out.println("代理方法："  + method.getName());

		// 构造请求
		RpcRequest rpcRequest = RpcRequest.builder()
				.serviceName(method.getDeclaringClass().getName())
				.methodName(method.getName())
				.parameterTypes(method.getParameterTypes())
				.args(args)
				.build();
		try {
			// 序列化
			byte[] bodyBytes = serializer.serialize(rpcRequest);
			// 发送请求
			try (HttpResponse httpResponse = HttpRequest.post("http://localhost:8080")
					.body(bodyBytes)
					.execute()) {
				byte[] result = httpResponse.bodyBytes();
				// 反序列化
				RpcResponse rpcResponse = serializer.deserialize(result, RpcResponse.class);
				return rpcResponse.getData();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
}
